/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;

import cn.hpclub.server.model.MemberOrg;
import com.google.common.net.MediaType;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.SmsCode;
import cn.hpclub.server.util.HttpUtil;
import cn.hpclub.server.util.SystemConfigUtil;

/**
 * Class description goes here
 *
 * @author
 */
public class SmsService{

    private static final Logger logger           = LoggerFactory.getLogger(SmsService.class);
    public static SmsService    service          = new SmsService();

    public final static String  RZL_PHONE        = "phone_no";
    public final static String  RZL_PWD          = "smsPwd";
    public final static String  RZL_RAW          = "rawStr";
    public final static String  RZL_RESULT       = "res_code";
    public final static String  RZL_MSG          = "res_msg";
    public final static String  RZL_SUCCESS      = "0000000";
    private String              CMCC_HOST_PREFIX = SystemConfigUtil.getSystemConfig().getCmccHostPrefix();
    private String              ESB_HOST_PREFIX = SystemConfigUtil.getSystemConfig().getEsbHostPrefix();

    public JSONObject SendSmsCode(String phone){

        try{
            // for debug，flq
            if(ClientApiConstant.SMS_CODE_DEBUG){
                return new JSONObject().put(RZL_RESULT, RZL_SUCCESS).put(RZL_MSG, "短信发送成功");
            }

            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put(RZL_PHONE, phone);
            return new JSONObject(SmsService.service.sendRandPass(SmsService.service.getRawStr(hm)));
            // if(result.getString(RZL_RESULT).equals(SmsService.service.RZL_SUCCESS)){
            // return true;
            // } else{
            // return false;
            // }
        } catch(Exception e){
            e.printStackTrace();
            return null;
        }

    }

    public JSONObject VerifySignCode(String phone, String smspwd){
        try{
            // for debug,flq
            if(ClientApiConstant.SMS_CODE_DEBUG){
                return verifyConstantSmsCode(smspwd);
            }

            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put(RZL_PHONE, phone);
            hm.put(RZL_PWD, smspwd);
            return new JSONObject(SmsService.service.validRandPass(SmsService.service.getRawStr(hm)));

        } catch(Exception e){
            e.printStackTrace();
            return null;
        }

        }

    public JSONObject VerifySignCodeLogin(String phone, String smspwd){
        try{
            // for debug,flq
            if(ClientApiConstant.SMS_CODE_DEBUG){
                return verifyConstantSmsCode(smspwd);
            }

            // 登录验证当天使用缓存记录
            if(SmsCode.dao.verifyCodeLogin(phone, smspwd)){
                //return new JSONObject().put(SmsService.service.RZL_RESULT, SmsService.service.RZL_SUCCESS);
                return new JSONObject().put("ROOT", new JSONObject().put("RETURN_CODE",0).put("USER_MSG",
                        "验证随机码成功"));
            } else{
                HashMap<String, Object> hm = new HashMap<String, Object>();
                hm.put(RZL_PHONE, phone);
                hm.put(RZL_PWD, smspwd);
                //JSONObject jo = new JSONObject(SmsService.service.validRandPass(SmsService.service.getRawStr(hm)));
                //(String phoneNumber,String empCode,int passmode,String smsCode){
                MemberOrg memberOrg = MemberOrg.dao.getMemberOrgbyUserName(phone);
                String empCode = memberOrg.getStr(MemberOrg.EMP_CODE);
                JSONObject jo = SmsService.service.sendOrCheckSmsCode(phone,empCode,1,smspwd);
                if(jo.getJSONObject("ROOT").getLong("RETURN_CODE")==0){
                    SmsCode.dao.updateCodeLogin(phone, smspwd);
                }
                return jo;
            }

        } catch(Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * @Title: verifyConstantSmsCode
     * @Description:TODO
     * @param smspwd
     * @return JSONObject
     */

    public JSONObject verifyConstantSmsCode(String smspwd){
        if(ClientApiConstant.CONSTANT_SMS_CODE.equalsIgnoreCase(smspwd)){
            JSONObject smsVerifyResult = new JSONObject();



            JSONObject subObject = new JSONObject();
            subObject.put("RETURN_CODE",0);
            subObject.put("RETURN_MSG","ok");
            subObject.put("USER_MSG","验证验证码成功");
            smsVerifyResult.put("ROOT",subObject);
            return smsVerifyResult;

        } else{
            JSONObject smsVerifyResult = new JSONObject();
            JSONObject subObject = new JSONObject();
            subObject.put("RETURN_CODE",0000001);
            subObject.put("RETURN_MSG","failed");
            subObject.put("USER_MSG","验证码错误");
            smsVerifyResult.put("ROOT",subObject);
            return smsVerifyResult;
        }
    }

    public String getRawStr(HashMap<String, Object> hm){
        try{

            String params = "";
            Iterator iterator = hm.keySet().iterator();
            while(iterator.hasNext()){
                String key = iterator.next().toString();
                logger.debug("key=" + key);
                logger.debug("v=" + hm.get(key).toString());
                params += key + "=" + URLEncoder.encode(hm.get(key).toString(), "UTF8") + "|";
            }
            if(params.length() > 0){
                params = params.substring(0, params.length() - 1);
            }
            logger.debug("p=" + params);
            hm = new HashMap<String, Object>();
            hm.put(RZL_RAW, params);

            JSONObject result = new JSONObject(HttpUtil.getHttpByPost(CMCC_HOST_PREFIX + Constant.Url.ENCODE_URL, hm));
            return result.getString(RZL_RAW);
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public String sendSmsRequest(String url, String str){
        try{
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put("rawStr", str);
            return HttpUtil.getHttpByPost(url, hm);
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public String sendRandPass(String str){
        try{
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put("rawStr", str);
            return HttpUtil.getHttpByPost(CMCC_HOST_PREFIX + Constant.Url.SEND_RAND_PASS, hm);
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @describe 此方法已过时，新的替代方法为:SmsService.sendOrCheckSmsCode
     * @param str
     * @return
     */
    @Deprecated
    public String validRandPass(String str){
        try{
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put("rawStr", str);
            return HttpUtil.getHttpByPost(CMCC_HOST_PREFIX + Constant.Url.VALID_RAND_PASS, hm);
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }



    /**
     * @describe 此接口为能力开放平台迁移到esb新的获取验证码接口
     * @param phoneNumber 手机号
     * @param empCode 工号
     * @param passmode 调取类型：0表示发送验证码，1表示验证验证码是否正确
     * @param smsCode 要验证的验证码，passmode为0时，smsCode传""
     * @return
     */
    public JSONObject sendOrCheckSmsCode(String phoneNumber,String empCode,int passmode,String smsCode){
        String resultStr = "";
        String data = "{" +
                "    \"BODY\": {" +
                "\"OLD_SERVER\": \"sRandSmsPwd\"," +
                "\"SERVICE_NO\": \""+phoneNumber+"\"," +
                "\"PROVINCE_GROUP\": \"10008\"," +
                "\"LOGIN_NO\": \""+empCode+"\"," +
                "\"PHONE_NO\": \""+phoneNumber+"\"," +
                "\"PASS_MODE\": \""+passmode+"\"," +
                "\"SMS_PWD\": \""+smsCode+"\"," +
                "\"PASS_LENGTH\": \"6\"}" +
                "}";


        try {
            resultStr = HttpUtil.syncPostJsonBody(ESB_HOST_PREFIX+"sQryRandPass", MediaType.FORM_DATA,data, 30000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JSONObject(resultStr);
    }




    public void clearRandPassLogin(){
        try{
            Db.update("delete from " + Constant.Table.SMS_CODE_LOGIN
                    + " where date_format(modify_time,'%Y-%m-%d')!=date_format(now(),'%Y-%m-%d')");
        } catch(Exception e){

        }
    }

    public void clearSmsCodeRecord(){
        try{

            Db.update("delete from " + Constant.Table.SMS_CODE_RECORD
                    + " where date_format(modify_time,'%Y-%m-%d')!=date_format(now(),'%Y-%m-%d')");
        } catch(Exception e){

        }
    }


}
